'RKD nmspc: 20120610 :: Imports EntertainmentManager
Imports BusinessLogicLayer.BLMain
Imports BusinessLogicLayer.BLException
Imports System.Data.SqlClient
Imports UniversalLayer
Imports UniversalLayer.ULMain
Imports UniversalLayer.ULDataHandler

''' <summary>
''' NO COMMENTS
''' </summary>
''' <remarks></remarks>
Public Class DLMain

    ''' <summary>
    ''' Behaviour for default poster, if file not found
    ''' </summary>
    ''' <remarks></remarks>
    Public Enum ePosterParent
        ''' <summary>
        ''' Search grid
        ''' </summary>
        ''' <remarks></remarks>
        Grid = 0
        ''' <summary>
        ''' Item preview
        ''' </summary>
        ''' <remarks></remarks>
        Preview = 1
        ''' <summary>
        ''' Details screen
        ''' </summary>
        ''' <remarks></remarks>
        Details = 2
        ''' <summary>
        ''' Splash screen
        ''' </summary>
        ''' <remarks></remarks>
        Splash = 3
    End Enum

    Public arrComparatorsAll() As String = {"as", "=", "<>", ">", "<", ">=", "<=", "in", "not in", "like", "not like", "sounds"}
    Public arrComparatorsString() As String = {"as", "=", "<>", "in", "not in", "like", "not like", "sounds"}
    Public arrComparatorsStringMax() As String = {"as", "like", "not like"}
    Public arrComparatorsMath() As String = {"=", "<>", ">", "<", ">=", "<="}
    Public arrBinaryComparators() As String = {"="}
    Public ReadOnly sFieldsAll As String ' = "Title,Alternate Title,Director,Number,Seen,Plot,Cast,Notes,Runtime,Country,Genre,Studio,Discs,IMDbCode"
    Public ReadOnly sFieldsString As String ' = "Title,Alternate Title,Director,Rating,Country,Genre,Studio,IMDbCode"
    Public ReadOnly sFieldsStringMax As String ' = "Plot,Cast,Notes"
    Public ReadOnly sFieldsNumeric As String ' = "Number,Rating,Runtime,Discs"
    Public ReadOnly sFieldsBinary As String ' = "Seen,Loaned"
    Public Shared ReadOnly sWatchlistColumns As String = "const,You rated,IMDb Rating,Num. Votes"
    Private arrBlankString() As String = {}

    Public dtMuvee As New DataTable
    'Public Const iBooleanStyle As eBooleanStyle = eBooleanStyle.Chr
    'Dim _DLCon As New DLConnector

    Public Sub New()
        Dim _DLSettings As DLSettings
        Try
            _DLSettings = New DLSettings
            ''sFieldsAll = "Title,Alternate Title,Director,Number,Seen,Plot,Cast,Notes,Runtime,Country,Genre,Studio,Discs,IMDbCode"
            ''sFieldsString = "Title,Alternate Title,Director,Rating,Country,Genre,Studio,IMDbCode"
            ''sFieldsStringMax = "Plot,Cast,Notes"
            ''sFieldsNumeric = "Number,Rating,Runtime,Discs"
            ''sFieldsBinary = "Seen,Loaned"
            sFieldsAll = CStr(_DLSettings.FetchOneSetting("Fields", "All"))
            sFieldsString = CStr(_DLSettings.FetchOneSetting("Fields", "String"))
            sFieldsStringMax = CStr(_DLSettings.FetchOneSetting("Fields", "StringMax"))
            sFieldsNumeric = CStr(_DLSettings.FetchOneSetting("Fields", "Numeric"))
            sFieldsBinary = CStr(_DLSettings.FetchOneSetting("Fields", "Binary"))

            InitializeDataTable(dtMuvee)
        Finally
            _DLSettings = Nothing
        End Try
    End Sub

    Private Sub InitializeDataTable(ByRef dtMuvee As DataTable)
        'RKD: PENDING_20120524: incorporate_series_details_fields()
        dtMuvee.Columns.Add("PKey")
        dtMuvee.Columns.Add("StagePKey")
        dtMuvee.Columns.Add("SerialNo")
        dtMuvee.Columns.Add("tmpSeen")
        dtMuvee.Columns.Add("tmpLoaned")
        dtMuvee.Columns.Add("Title")
        dtMuvee.Columns.Add("AlternateTitle")
        dtMuvee.Columns.Add("ID")
        dtMuvee.Columns.Add("Seen")
        dtMuvee.Columns.Add("Rating")
        dtMuvee.Columns.Add("MyRating")
        dtMuvee.Columns.Add("Director")
        dtMuvee.Columns.Add("Volume")
        dtMuvee.Columns.Add("Genre")
        dtMuvee.Columns.Add("Year")
        dtMuvee.Columns.Add("Studio")
        dtMuvee.Columns.Add("Collection")
        dtMuvee.Columns.Add("Cast")
        dtMuvee.Columns.Add("Plot")
        dtMuvee.Columns.Add("Notes")
        dtMuvee.Columns.Add("Country")
        dtMuvee.Columns.Add("Poster_Loc")
        dtMuvee.Columns.Add("Classification")
        dtMuvee.Columns.Add("nDiscs")
        dtMuvee.Columns.Add("RunTime")
        dtMuvee.Columns.Add("Layer")
        dtMuvee.Columns.Add("Colour")
        dtMuvee.Columns.Add("Region")
        dtMuvee.Columns.Add("Medium")
        dtMuvee.Columns.Add("VCodec")
        dtMuvee.Columns.Add("ACodec")
        dtMuvee.Columns.Add("Condition")
        dtMuvee.Columns.Add("IMDbLink")
        dtMuvee.Columns.Add("IMDbTrailerLink")
        dtMuvee.Columns.Add("OfficialSite")
        dtMuvee.Columns.Add("WikipediaLink")
        dtMuvee.Columns.Add("MyReviews")
        dtMuvee.Columns.Add("Status")

        dtMuvee.Columns.Add("VolumeMainPKey")
        dtMuvee.Columns.Add("CollectionMainPKey")
        dtMuvee.Columns.Add("LayerMainPKey")
        dtMuvee.Columns.Add("ColourMainPKey")
        dtMuvee.Columns.Add("RegionMainPKey")
        dtMuvee.Columns.Add("MediumMainPKey")
        dtMuvee.Columns.Add("VCodecMainPKey")
        dtMuvee.Columns.Add("ACodecMainPKey")
        dtMuvee.Columns.Add("CondMainPKey")
    End Sub

#Region "Format CSV"

    ''' <summary>
    ''' Creates a list of comma-separated values
    ''' </summary>
    ''' <param name="sString">String to be converted</param>
    ''' <param name="sReplacements">Array of Replacements before splitting: old/new values (in order)</param>
    ''' <param name="cDelimiter">Delimiter to split</param>
    ''' <param name="cSeparator">Separator for each item</param>
    ''' <remarks></remarks>
    Public Sub CreateCSVList(ByRef sString As String, ByVal sReplacements(,) As String, Optional ByVal cDelimiter As Char = ","c, Optional ByVal cSeparator As Char = "'"c)
        Dim arrSplit() As String
        Dim iOuter As Integer

        Try
            'ReDim Preserve sReplacements(CInt(sReplacements.Length / 2), 1)
            For iOuter = 0 To CInt(sReplacements.Length / 2) - 1
                sString = sString.Replace(sReplacements(iOuter, 0), sReplacements(iOuter, 1))
            Next

            For Each sEachReplacement As String In sReplacements
                sString = sString.Replace(sEachReplacement(0), sEachReplacement(1))
            Next
            arrSplit = sString.Trim(cDelimiter).Split(cDelimiter)

            sString = ""
            AddArrayToList(sString, arrSplit)

        Catch ex As Exception
            ThrowBLException(ex, "DataAccessLayer.DLMain.CreateCSVList")
            '_BLException = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' NO COMMENTS
    ''' </summary>
    ''' <param name="dcTable"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ConvertDataColumnToArray(ByVal dcTable As DataColumn) As String()
        Dim arrItems() As String

        For i As Integer = 0 To dcTable.Table.Rows.Count - 1
            'dcTable.
            'MsgBox(dcTable.Table.Rows(i).Item(0).ToString)
        Next

        Return arrItems
    End Function

#End Region

    ''' <summary>
    ''' Fetches default poster
    ''' </summary>
    ''' <param name="dtSettingsMain">DataTable containing all settings</param>
    ''' <param name="iPosterParent">Poster parent control</param>
    ''' <!--param name="sPosterExtension">Poster file extension</param-->
    ''' <remarks></remarks>
    Private Shared Sub FetchDefaultPosterPath(ByRef dtSettingsMain As DataTable, ByRef sPosterPath As String, _
    ByVal iPosterParent As ePosterParent) ', Optional ByVal sPosterExtension As String = "")
        Dim sPosterDirectory, sPosterExtn As String
        Dim sDefaultFileName As String = ""

        Try
            'If IsEmpty(_DLSettings) Then _DLSettings = New DLSettings
            'sPosterPath = CStr(_DLSettings.FetchOneSetting("Poster", "Path")).TrimEnd("\"c)
            'sPosterDirectory = CStr(_DLSettings.FetchOneSetting("Poster", "Path")).TrimEnd("\"c)
            'RKD : 20120610 :: sPosterDirectory = frmEntertainmentManager.sApplicationPath & "\img"
            Select Case iPosterParent
                Case ePosterParent.Preview, ePosterParent.Details
                    'sPosterPath &= "\" & CStr(_DLSettings.FetchOneSetting("Poster", "Default")).TrimEnd("\.".ToCharArray)
                    sDefaultFileName = CStr(DLSettings.FetchOneSetting(dtSettingsMain, "Poster", "Default")).TrimEnd("\"c)
                Case ePosterParent.Grid
                    'sPosterPath &= "\" & CStr(_DLSettings.FetchOneSetting("Poster", "DefaultGrid")).TrimEnd("\.".ToCharArray)
                    sDefaultFileName = CStr(DLSettings.FetchOneSetting(dtSettingsMain, "Poster", "DefaultGrid")).TrimEnd("\"c)
                Case ePosterParent.Splash
                    'sPosterPath &= "\" & CStr(_DLSettings.FetchOneSetting("Splash", "Default")).TrimEnd("\.".ToCharArray)
                    'sPosterDirectory = EntertainmentManager.frmEntertainmentMgr.sApplicationPath & "\img"
                    sDefaultFileName = CStr(DLSettings.FetchOneSetting(dtSettingsMain, "Splash", "Default")).TrimEnd("\"c)
            End Select
            'sPosterPath &= "." & CStr(IIf(Not IsEmpty(sPosterExtension), sPosterExtension, _DLSettings.FetchOneSetting("Poster", "Extension")))
            sPosterExtn = CStr(DLSettings.FetchOneSetting(dtSettingsMain, "Poster", "Extension")).TrimStart("."c)

            'sPosterPath = sPosterDirectory & "\" & sDefaultFileName & "." & sPosterExtn
            sPosterPath = CreatePosterPath(dtSettingsMain, sDefaultFileName, sPosterDirectory, iPosterParent, sPosterExtn)
        Finally

        End Try
    End Sub

    ''' <summary>
    ''' Creates Absolute Path from Poster name
    ''' </summary>
    ''' <param name="dtSettingsMain">DataTable containing all settings</param>
    ''' <param name="sPosterName">Poster name</param>
    ''' <param name="sPosterDirectory">Directory containing image file (optional)</param>
    ''' <param name="iPosterParent">Poster parent control</param>
    ''' <param name="sPosterExtension">Poster file extension</param>
    ''' <returns>Absoulte Path of poster</returns>
    ''' <remarks></remarks>
    Public Shared Function CreatePosterPath(ByVal dtSettingsMain As DataTable, ByVal sPosterName As String, _
    Optional ByVal sPosterDirectory As String = "", Optional ByVal iPosterParent As ePosterParent = ePosterParent.Grid, _
    Optional ByVal sPosterExtension As String = "") As String
        'Public Shared Function CreatePosterPath(ByVal sPosterName As String, ByVal sPosterDirectory As String, ByVal iPosterParent As ePosterParent) As String
        Dim sPosterPath As String = ""
        Dim _DLSetings As DLSettings

        Try
            If IsEmpty(dtSettingsMain) Then
                _DLSetings = New DLSettings
                dtSettingsMain = _DLSetings.FetchAllSettings
            End If

            If Not IsEmpty(sPosterName) Then
                If IsEmpty(sPosterDirectory) Then sPosterDirectory = CStr(DLSettings.FetchOneSetting(dtSettingsMain, "Poster", "Path"))
                sPosterExtension = CStr(IIf(Not IsEmpty(sPosterExtension), sPosterExtension, DLSettings.FetchOneSetting(dtSettingsMain, "Poster", "Extension")))
                sPosterPath = sPosterDirectory.TrimEnd("\"c) & "\" & sPosterName & "." & sPosterExtension
                'DLMain.CreatePosterPath(sPosterName, sPosterDirectory, iPosterParent, sPosterExtension)
            End If

            'Fetch default poster, if file name not mention or file does not exist
            If IsEmpty(sPosterName) Or Not IsFileExists(sPosterPath) Then _
                FetchDefaultPosterPath(dtSettingsMain, sPosterPath, iPosterParent)
            Return sPosterPath

        Finally
            _DLSetings = Nothing
            sPosterPath = Nothing
            sPosterDirectory = Nothing
            sPosterExtension = Nothing
        End Try
    End Function

    ''' <summary>
    ''' Creates Absolute Path for default poster
    ''' </summary>
    ''' <param name="bSelectDefault">TRUE: Selects default poster</param>
    ''' <param name="iPosterParent">Poster parent control</param>
    ''' <returns>Absoulte Path of default poster</returns>
    ''' <remarks></remarks>
    Public Shared Function CreatePosterPath(ByVal dtSettingsMain As DataTable, ByVal bSelectDefault As Boolean, ByVal iPosterParent As ePosterParent) As String
        Dim sPosterDirectory As String
        Try
            'RKD : 20120610 :: sPosterDirectory = frmEntertainmentManager.sApplicationPath & "\img\"
            Return CStr(IIf(Not bSelectDefault, "", DLMain.CreatePosterPath(dtSettingsMain, "", sPosterDirectory, iPosterParent, "jpg")))
        Finally
            sPosterDirectory = Nothing
        End Try
    End Function

    ''' <summary>
    ''' NO COMMENTS
    ''' </summary>
    ''' <param name="dtCSV"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ConvertToCSV(ByVal dtCSV As DataTable) As String

    End Function

    







    Public Shared Function FetchDBViewName(ByVal iEntertainmentType As eEntertainmentType) As String
        Select Case iEntertainmentType
            Case eEntertainmentType.Muvees : Return "MuveeDetailsView"
            Case eEntertainmentType.TVSeries : Return "SeriesDetailsView"
        End Select
    End Function

    Public Enum eRelativeDate
        DayBeforeYesterday = -2
        Yesterday = -1
        Today = 0
        Tomorrow = 1
        DayAfterTomorrow = 2

        NextSaturday = -107
        NextFriday
        NextThursday
        NextWednesday
        NextTuesday
        NextMonday
        NextSunday

        LastSunday = 101
        LastMonday
        LastTuesday
        LastWednesday
        LastThursday
        LastFriday
        LastSaturday

        LastYear = 502
        LastMonth = -501
        NextMonth = 501
        NextYear = 502
    End Enum

    Public Function FormatRelativeDates(ByVal iRelativeDate As eRelativeDate) As DateTime
        Select Case iRelativeDate
            ''Case eRelativeDate.DayBeforeYesterday : Return DateAdd(DateInterval.Day, -2, Now)
            ''Case eRelativeDate.Yesterday : Return DateAdd(DateInterval.Day, -1, Now)
            ''Case eRelativeDate.Today : Return DateAdd(DateInterval.Day, 0, Now)
            ''Case eRelativeDate.Tomorrow : Return DateAdd(DateInterval.Day, 1, Now)
            ''Case eRelativeDate.DayAfterTomorrow : Return DateAdd(DateInterval.Day, 2, Now)
            Case eRelativeDate.DayBeforeYesterday, eRelativeDate.Yesterday, _
            eRelativeDate.Today, eRelativeDate.Tomorrow, eRelativeDate.DayAfterTomorrow
                Return DateAdd(DateInterval.Day, CInt(iRelativeDate), Now)

            Case eRelativeDate.LastSunday
            Case eRelativeDate.LastMonday
            Case eRelativeDate.LastTuesday
            Case eRelativeDate.LastWednesday
            Case eRelativeDate.LastThursday
            Case eRelativeDate.LastFriday
            Case eRelativeDate.LastSaturday

            Case eRelativeDate.NextSunday
            Case eRelativeDate.NextMonday
            Case eRelativeDate.NextTuesday
            Case eRelativeDate.NextWednesday
            Case eRelativeDate.NextThursday
            Case eRelativeDate.NextFriday
            Case eRelativeDate.NextSaturday
        End Select
    End Function





    ''''' <summary>
    ''''' Creates and returns a new DataTable based on rows from an existing DataTable
    ''''' </summary>
    ''''' <param name="dtSource">Original DataTable</param>
    ''''' <param name="dtDistinct">DataTable containing distinct values</param>
    ''''' <param name="sColumnNames">A string array that contains a list of the column names to be included 
    ''''' in the returned System.Data.DataTable. The DataTable contains the specified columns
    ''''' in the order they appear within this array.</param>
    ''''' <remarks></remarks>
    ''Public Sub SelectDistinct(ByVal dtSource As DataTable, ByRef dtDistinct As DataTable, ByVal sColumnNames As String, ByVal sCondition As String)
    ''    Try
    ''        sCondition = "" 'DEBUG: bypass logic
    ''        'If IsEmpty(sCondition) Then sCondition = "(1=1)"
    ''        If Not IsEmpty(sCondition) Then
    ''            sCondition &= " AND Status <> 'd'"
    ''            Dim drSelected() As DataRow = dtSource.Select(sCondition)
    ''            Dim dtTemp As New DataTable
    ''
    ''            CopyDataTable(dtSource, dtTemp, , True)
    ''            For Each dr As DataRow In drSelected
    ''                dtTemp.Rows.Add(dr.ItemArray)
    ''            Next
    ''            dtSource.Rows.Clear()
    ''            CopyDataTable(dtTemp, dtSource)
    ''        End If
    ''
    ''        dtDistinct = dtSource.DefaultView.ToTable(True, sColumnNames.Replace(" ", "").Split(","c))
    ''        If IsEmpty(dtDistinct.TableName) Then dtDistinct.TableName = "Distinct_" & dtSource.TableName & "_" & sColumnNames.Replace(" ", "").Replace(",", "_")
    ''
    ''    Finally
    ''
    ''    End Try
    ''End Sub




    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' This Function returns a dataTable that contains distinct values
    ''' </summary>
    ''' <param name="SourceTable">dataTable to be filtered for Distinct Selected values</param>
    ''' <param name="FieldNames">String of Column Names of the Source DataTable to be filtered and to be displayed</param>
    ''' <returns> a dataTable that contains distinct values</returns>
    ''' <remarks>
    ''' http://social.msdn.microsoft.com/forums/en-US/adodotnetdataset/thread/ed9c6a6a-a93e-4bf5-a892-d8471b84aa3b/
    ''' </remarks>
    ''' <history>
    '''    [Victor]   10/25/2006   Created
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Friend Function SelectDistinct(ByVal SourceTable As DataTable, ByVal ParamArray FieldNames() As String) As DataTable
        Dim lastValues() As Object
        Dim newTable As DataTable

        If FieldNames Is Nothing OrElse FieldNames.Length = 0 Then
            Throw New ArgumentNullException("FieldNames")
        End If

        lastValues = New Object(FieldNames.Length - 1) {}
        newTable = New DataTable

        For Each field As String In FieldNames
            newTable.Columns.Add(field, SourceTable.Columns(field).DataType)
        Next

        For Each Row As DataRow In SourceTable.Select("", String.Join(", ", FieldNames))
            If Not FieldValuesAreEqual(lastValues, Row, FieldNames) Then
                newTable.Rows.Add(CreateRowClone(Row, newTable.NewRow(), FieldNames))

                setLastValues(lastValues, Row, FieldNames)
            End If
        Next

        Return newTable
    End Function

    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' This function returns a boolean value to test whether 2 values are equal or not
    ''' </summary>
    ''' <param name="lastValues">The last value to being tested</param>
    ''' <param name="currentRow">The current dataRow being tested</param>
    ''' <param name="fieldNames">The fieldNames in the DataRow</param>
    ''' <returns>A boolean value to test whether 2 values are equal or not</returns>
    ''' <remarks>
    ''' http://social.msdn.microsoft.com/forums/en-US/adodotnetdataset/thread/ed9c6a6a-a93e-4bf5-a892-d8471b84aa3b/
    ''' </remarks>
    ''' <history>
    '''    [Victor]   10/25/2006   Created
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Private Function FieldValuesAreEqual(ByVal lastValues() As Object, ByVal currentRow As DataRow, ByVal fieldNames() As String) As Boolean
        Dim areEqual As Boolean = True

        For i As Integer = 0 To fieldNames.Length - 1
            If lastValues(i) Is Nothing OrElse Not lastValues(i).Equals(currentRow(fieldNames(i))) Then
                areEqual = False
                Exit For
            End If
        Next

        Return areEqual
    End Function

    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' This function returns a datarow created from the source dataRow to be populated with distinct values
    ''' </summary>
    ''' <param name="sourceRow">Source DataRow</param>
    ''' <param name="newRow">Target DataRow</param>
    ''' <param name="fieldNames">Column Names in the DataRow</param>
    ''' <returns>A datarow created from the source dataRow to be populated with distinct values</returns>
    ''' <remarks>
    ''' http://social.msdn.microsoft.com/forums/en-US/adodotnetdataset/thread/ed9c6a6a-a93e-4bf5-a892-d8471b84aa3b/
    ''' </remarks>
    ''' <history>
    '''    [Victor]   10/25/2006   Created
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Private Function CreateRowClone(ByVal sourceRow As DataRow, ByVal newRow As DataRow, ByVal fieldNames() As String) As DataRow
        For Each field As String In fieldNames
            newRow(field) = sourceRow(field)
        Next

        Return newRow
    End Function

    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' This is a method that is used to set the last values in a DataRow
    ''' </summary>
    ''' <param name="lastValues">An object array that contains that will contain last values</param>
    ''' <param name="sourceRow">source datarow that contains the last values to be imported</param>
    ''' <param name="fieldNames">Column Names of the Source Row</param>
    ''' <remarks>
    ''' http://social.msdn.microsoft.com/forums/en-US/adodotnetdataset/thread/ed9c6a6a-a93e-4bf5-a892-d8471b84aa3b/
    ''' </remarks>
    ''' <history>
    '''    [Victor]   10/25/2006   Created
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Private Sub setLastValues(ByVal lastValues() As Object, ByVal sourceRow As DataRow, ByVal fieldNames() As String)
        For i As Integer = 0 To fieldNames.Length - 1
            lastValues(i) = sourceRow(fieldNames(i))
        Next
    End Sub
End Class
